package com.studentgrowth.controller.auth;

import com.studentgrowth.common.api.Result;
import com.studentgrowth.model.auth.User;
import com.studentgrowth.service.auth.UserService;
import com.studentgrowth.config.security.SecurityConfig;
import com.studentgrowth.dto.auth.LoginRequest;
import com.studentgrowth.dto.auth.RegisterRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    
    private final UserService userService;
    
    @Autowired
    private SecurityConfig securityConfig;

    public AuthController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/register")
    public Result<String> register(@RequestBody RegisterRequest request) {
        // 验证两次密码是否一致
        if (!request.getPassword().equals(request.getConfirmPassword())) {
            return Result.failed("两次输入的密码不一致");
        }
        try {
            userService.register(request.getUsername(), request.getPassword());
            return Result.success("注册成功");
        } catch (RuntimeException e) {
            return Result.failed(e.getMessage());
        } catch (Exception e) {
            return Result.failed("系统异常，请稍后重试");
        }
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest request) {
        try {
            User user = userService.login(request.getUsername(), request.getPassword());
            if (user != null) {
                String token = securityConfig.generateToken(user.getId());
                Map<String, Object> response = new HashMap<>();
                response.put("code", 200);
                response.put("message", "登录成功");
                response.put("token", token);
                response.put("userId", user.getId());
                return ResponseEntity.ok(response);
            }
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", "用户名或密码错误");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "系统异常，请稍后重试");
            return ResponseEntity.ok(response);
        }
    }
} 